package org.example.news_check.ServiceImpl;

import org.example.news_check.Pojo.Communicate;
import org.example.news_check.Mapper.CommunicateMapper;
import org.example.news_check.Service.CommunicateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CommunicateImpl implements CommunicateService {
    @Autowired

    private final CommunicateMapper communicateMapper;

    @Autowired
    public CommunicateImpl(CommunicateMapper communicateMapper) {
        this.communicateMapper = communicateMapper;
    }

    @Override
    public List<Communicate> listTree() {
        List<Communicate> list = communicateMapper.selectList(); // 使用MyBatis风格的Mapper方法

        HashMap<Integer, Integer> map = new HashMap<>();
        for (int index = 0; index < list.size(); index++) {
            map.put(list.get(index).getId(), index);
        }

        for (Communicate communicate : list) {
            Integer pid = communicate.getPid();
            if (pid != null) {
                Integer indexFather = map.get(pid);
                if (indexFather != null) {
                    Communicate father = list.get(indexFather);
                    if (father.getChildren() == null) {
                        father.setChildren(new ArrayList<>());
                    }
                    father.getChildren().add(communicate);
                }
            }
        }

        return list.stream().filter(child -> child.getPid() == null).collect(Collectors.toList());
    }

    @Override
    public void save(Communicate communicate) {
        communicateMapper.insert(communicate);
    }

    @Override
    public List<Communicate> listTreeByArticleId(Integer articleId) {
        // 查询所有与文章 ID 相关的评论
        List<Communicate> list = communicateMapper.selectByArticleId(articleId);

        // 构建父子关系映射
        HashMap<Integer, Communicate> map = new HashMap<>();
        for (Communicate communicate : list) {
            map.put(communicate.getId(), communicate);
        }

        // 构建树形结构
        for (Communicate communicate : list) {
            Integer pid = communicate.getPid();
            if (pid != null) {
                Communicate father = map.get(pid);
                if (father != null) {
                    if (father.getChildren() == null) {
                        father.setChildren(new ArrayList<>());
                    }
                    father.getChildren().add(communicate);
                }
            }
        }

        // 返回根评论
        return list.stream().filter(child -> child.getPid() == null).collect(Collectors.toList());
    }
}
